import React from 'react'

import ReportContent from "../../components/Report";
import {secs2time, ts2time} from "../../utils/utils";
import moment from "moment";
import {fetchErrorReportData} from "../../services/report";


const handleDataFormat = (data, type) => {
  if (!data) return;
  if (type === 'detail') {
    return data.map((item, idx) => {
      const {
        id,
        device_id,
        time,
        time_stamp,
        battery,
        lat,
        lng,
        loss_battery,
      } = item;
      const start_time = moment(time_stamp).format('YYYY-MM-DD hh:mm:ss')
      const end_time = moment(start_time).subtract(1, 'hours').format('YYYY-MM-DD hh:mm:ss');
      return {
        key: idx,
        device_id,
        start: `${lat / 1e6}, ${lng / 1e6}`,
        end: `${lat / 1e6}, ${lng / 1e6}`,
        start_xy: {lng: lng / 1e6, lat: lat / 1e6},
        end_xy: {lng: lng / 1e6, lat: lat / 1e6},
        error_type: '电量异常',
        start_time,
        end_time,
      }
    })
  }

  return data.map((item, idx) => {
    const {
      end_stamp,
      battery_error_count,
      device_id,
      start_stamp,
    } = item;
    return {
      key: idx,
      device_id,
      battery_error_count,
      start_time: moment(start_stamp).format('YYYY-MM-DD hh:mm:ss'),
      end_time: moment(end_stamp).format('YYYY-MM-DD hh:mm:ss'),
    }
  })
};


// # 设备编号  开始时间 结束时间 明细
const columnsDay = (handleDetailClick) => ([
  {
    dataIndex: "device_id",
    title: "设备编号"
  },
  {
    dataIndex: "start_time",
    title: "开始时间"
  },
  {
    dataIndex: "end_time",
    title: "结束时间"
  },
  {
    dataIndex: "battery_error_count",
    title: "电量异常"
  },
  {
    title: '操作',
    dataIndex: '',
    key: 'x',
    render: (text, record, index) => <a href="javascript:"
                                        onClick={handleDetailClick(text, record)}>明细</a>,
  },
]);


// # 设备编号 异常内容 开始时间 结束时间 开始位置 结束位置 持续时长
const columnsDetail = (handleTableClick) => ([
  {
    dataIndex: "device_id",
    title: "设备编号"
  },
  {
    dataIndex: "error_type",
    title: "异常内容"
  },
  {
    dataIndex: "start_time",
    title: "开始时间"
  },
  {
    dataIndex: "end_time",
    title: "结束时间"
  },
  {
    dataIndex: "start",
    title: "开始位置",
    render: (text, record, index) => (
      <span>
            <a href="javascript:" onClick={handleTableClick(record.start_xy, index)}>{text}</a>
          </span>
    ),
  },
  {
    dataIndex: "end",
    title: "结束位置",
    render: (text, record, index) => (
      <span>
            <a href="javascript:" onClick={handleTableClick(record.start_xy, index)}>{text}</a>
          </span>
    ),
  }
]);

const Error = (props) => (
  <ReportContent {...props} title="异常报表" fetch={fetchErrorReportData} handleDataFormat={handleDataFormat}
                 columnsDay={columnsDay}
                 columnsDetail={columnsDetail}
                 showPolyline={true}
  />);


export default Error;
